package com.jerry.boot.admin.api.web;

import com.jerry.boot.admin.api.util.Permission;
import com.jerry.boot.admin.api.util.PermissionUtil;
import com.jerry.db.domain.BootRoleInfo;
import com.jerry.db.domain.BootUserInfo;
import com.jerry.db.service.BootPermissionInfoService;
import com.jerry.db.service.BootRoleInfoService;
import com.jerry.db.service.BootUserInfoService;
import com.jerry.frame.util.JacksonUtil;
import com.jerry.frame.util.ResponseUtil;
import com.jerry.frame.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static com.jerry.boot.admin.api.constant.AdminResponseCode.ADMIN_INVALID_ACCOUNT;
@RestController
@RequestMapping("/admin/auth")
public class AdminAuthController extends BaseController{
    @Autowired
    private BootPermissionInfoService bootPermissionInfoService ;
    @Autowired
    private BootUserInfoService bootUserInfoService;
    @Autowired
    private BootRoleInfoService bootRoleInfoService;

    private HashMap<String, String> systemPermissionsMap = null;
    @Autowired
    private ApplicationContext context;

    @PostMapping("/login")
    public Object login(@RequestBody String body) {
        String username = JacksonUtil.parseString(body, "username");
        String password = JacksonUtil.parseString(body, "password");

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return ResponseUtil.badArgument();
        }

        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.login(new UsernamePasswordToken(username, password));
        } catch (UnknownAccountException uae) {
            return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "用户帐号或密码不正确");
        } catch (LockedAccountException lae) {
            return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "用户帐号已锁定不可用");

        } catch (AuthenticationException ae) {
            return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "认证失败");
        }
        return ResponseUtil.ok(currentUser.getSession().getId());
    }

    @GetMapping("/info")
    public Object info(@RequestBody String body) {
        Subject currentUser = SecurityUtils.getSubject();
        BootUserInfo admin = (BootUserInfo) currentUser.getPrincipal();

        Map<String, Object> data = new HashMap<>();
        data.put("name", admin.getUserName());
        data.put("avatar", admin.getAvatar());

        String[] roleIds = admin.getRoleIds();
        //捞出所有的角色
        Set<String> roles = bootRoleInfoService.queryByIds(roleIds);
        //根据角色捞出所有的权限
        Set<String> permissions = bootPermissionInfoService.queryByRoleIds(roleIds);
        data.put("roles", roles);
        // NOTE
        // 这里需要转换perms结构，因为对于前端而已API形式的权限更容易理解
        //根据权限再捞出所有能访问的API
        data.put("perms", toAPI(permissions));
        return ResponseUtil.ok(data);
    }
    @RequiresAuthentication
    @PostMapping("/logout")
    public Object login() {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return ResponseUtil.ok();
    }


    private Collection<String> toAPI(Set<String> permissions) {
        if (systemPermissionsMap == null) {
            systemPermissionsMap = new HashMap<>();
            final String basicPackage = "com.jerry.boot.admin";
            List<Permission> systemPermissions = PermissionUtil.listPermission(context, basicPackage);
            for (Permission permission : systemPermissions) {
                String perm = permission.getRequiresPermissions().value()[0];
                String api = permission.getApi();
                systemPermissionsMap.put(perm, api);
            }
        }

        Collection<String> apis = new HashSet<>();
        for (String perm : permissions) {
            String api = systemPermissionsMap.get(perm);
            apis.add(api);

            if (perm.equals("*")) {
                apis.clear();
                apis.add("*");
                return apis;
//                return systemPermissionsMap.values();

            }
        }
        return apis;
    }
    public static void main(String[] args) {
        AdminAuthController adminAuthController = new AdminAuthController();
        adminAuthController.logger.info("111");
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        System.out.println(bCryptPasswordEncoder.encode("admin"));
    }
}
